package main

import (
	"CaptchaCluster/client/conf"
	"CaptchaCluster/cmd"
	"fmt"
	"github.com/BurntSushi/toml"
	"github.com/ying32/govcl/vcl"
	"io/ioutil"
	"os"
	"strings"
	"time"
)

//::private::
type TForm_MainFields struct {
}

var clientConf = new(conf.ClientConf)

var serverConf = `# 打码集群的管理端

LogLevel = "debug"              # 日志等级
TCPAddr = "0.0.0.0:3563"        # 服务器地址
MaxConnNum = 20000              # 最大客户端连接数

# nginx配置 ( 详情:http://nginx.org/en/docs/stream/ngx_stream_upstream_module.html )
[Nginx]
ReloadTimes = 1                # nginx重载配置间隔时间 单位:分钟

# 在FailTimeout设置的时间范围内,累计失败次数;
# 当达到上限值时,停止向该服务器发送数据,等待FailTimeout秒后再发送数据尝试. 直到恢复为止
MaxFails = 3

FailTimeout = 90                # 失败超时秒数`

func (f *TForm_Main) OnButton_StartServerClick(sender vcl.IObject) {
	ioutil.WriteFile("./conf/conf.toml", []byte(serverConf), 0644)

	command := []string{
		"@echo off",
		"reg add HKEY_CURRENT_USER\\Console /v QuickEdit /t REG_DWORD /d 00000000 /f",
		"start server.exe",
	}
	cmd.Start(5*time.Second, command...)
}

func (f *TForm_Main) OnButton_StartClientClick(sender vcl.IObject) {
	fmt.Println([]byte(f.Edit_ServerAddr.Text()))

	if clientConf == nil {
		clientConf = new(conf.ClientConf)
	}
	var err string
	if f.Edit_LocalName.Text() == "" {
		err = "name is empty\n"
	}
	if f.Edit_ServerAddr.Text() == "" {
		err += "server addr is empty\n"
	}

	seek, _ := cmd.StartWithKeyword(3*time.Second, cmd.GB18030, "TTL", "ping "+f.Edit_ServerAddr.Text())
	if !seek {
		err += fmt.Sprintf("failed to connect to server addr %s\n", f.Edit_ServerAddr.Text())
	}
	if err != "" {
		vcl.ShowMessage(err)
		return
	}

	clientConf.Name = f.Edit_LocalName.Text()
	clientConf.ServerAddr = f.Edit_ServerAddr.Text() + ":3563"
	saveClientConf()

	command := []string{
		"@echo off",
		"reg add HKEY_CURRENT_USER\\Console /v QuickEdit /t REG_DWORD /d 00000000 /f",
		"start client.exe",
	}
	cmd.Start(5*time.Second, command...)
}

func (f *TForm_Main) OnFormCreate(sender vcl.IObject) {
	// 隐藏page,根据需要显示
	for i := 0; i < int(f.PageControl1.PageCount()); i++ {
		f.PageControl1.Pages(int32(i)).SetTabVisible(false)
	}
	f.PageControl1.SetActivePageIndex(-1)

	// 根据根目录只显示对应的界面
	_, serverErr := os.Stat("server.exe")
	_, clientErr := os.Stat("client.exe")

	if serverErr == nil {
		f.TabSheet1.SetTabVisible(true)
		f.PageControl1.SetActivePageIndex(0)

		// ipconfig
		out, err := cmd.Start(3*time.Second, "ipconfig -h")
		if err != nil {
			vcl.ShowMessage(err.Error())
			os.Exit(0)
		}
		f.Memo_ServerIPAddr.SetText(out)

	}
	if clientErr == nil {
		f.TabSheet2.SetTabVisible(true)
		f.PageControl1.SetActivePageIndex(1)

		// 读取客户端配置
		_, err := toml.DecodeFile("./conf/conf.toml", clientConf)
		if err != nil {
			vcl.ShowMessage(err.Error())
			return
		} else {
			f.Edit_LocalName.SetText(clientConf.Name)

			addr := strings.Split(clientConf.ServerAddr, ":")
			f.Edit_ServerAddr.SetText(addr[0])
		}

	}
}

func saveClientConf() {
	file, err := os.OpenFile("./conf/conf.toml", os.O_RDWR|os.O_CREATE, 0644)
	if err != nil {
		vcl.ShowMessage(err.Error())
		return
	}
	defer file.Close()

	if clientConf == nil {
		clientConf = new(conf.ClientConf)
	}
	err = toml.NewEncoder(file).Encode(clientConf)
	if err != nil {
		vcl.ShowMessage(err.Error())
	}
}
